import type {
  Project,
  Task,
  TaskGroup,
  User
} from '../types/project';
import { TaskStatus, TaskPriority } from '../types/project';

// Mock users
const mockUsers: User[] = [
  { id: '1', name: '张三', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Zhang', email: 'zhang@example.com' },
  { id: '2', name: '李四', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Li', email: 'li@example.com' },
  { id: '3', name: '王五', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Wang', email: 'wang@example.com' },
  { id: '4', name: '赵六', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Zhao', email: 'zhao@example.com' },
  { id: '5', name: '钱七', avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Qian', email: 'qian@example.com' },
];

// Mock projects data
let mockProjects: Project[] = [
  {
    id: 'project-1',
    title: '前端重构项目',
    description: '将现有系统从 Vue 2 迁移到 Vue 3，并优化性能',
    creator: mockUsers[0],
    members: mockUsers.slice(0, 4),
    createdAt: '2024-01-15T10:00:00Z',
    updatedAt: '2024-01-20T15:30:00Z',
    groups: [
      {
        id: 'group-1',
        title: '待开始',
        color: '#f5f5f5',
        order: 0,
        createdAt: '2024-01-15T10:00:00Z',
        updatedAt: '2024-01-15T10:00:00Z',
        tasks: [
          {
            id: 'task-1',
            title: '技术方案调研',
            description: '调研 Vue 3 迁移方案，包括组件库兼容性、状态管理等',
            status: TaskStatus.NOT_STARTED,
            priority: TaskPriority.HIGH,
            assignee: mockUsers[1],
            creator: mockUsers[0],
            startDate: '2024-01-25T00:00:00Z',
            dueDate: '2024-02-05T00:00:00Z',
            milestone: 'M1 - 技术选型',
            groupId: 'group-1',
            createdAt: '2024-01-15T10:00:00Z',
            updatedAt: '2024-01-15T10:00:00Z',
            subTasks: [
              { id: 'subtask-1', title: '调研 Vue 3 新特性', completed: false, createdAt: '2024-01-15T10:00:00Z', updatedAt: '2024-01-15T10:00:00Z' },
              { id: 'subtask-2', title: '评估组件库兼容性', completed: false, createdAt: '2024-01-15T10:00:00Z', updatedAt: '2024-01-15T10:00:00Z' },
              { id: 'subtask-3', title: '制定迁移计划', completed: false, createdAt: '2024-01-15T10:00:00Z', updatedAt: '2024-01-15T10:00:00Z' },
            ],
            cards: [
              { id: 'card-1', title: '技术文档', description: 'Vue 3 迁移指南', content: '详细的迁移步骤和注意事项', createdAt: '2024-01-15T10:00:00Z', updatedAt: '2024-01-15T10:00:00Z' },
            ],
            tags: ['技术调研', '高优先级'],
            progress: 0,
          },
          {
            id: 'task-2',
            title: '依赖包升级评估',
            description: '评估现有依赖包在 Vue 3 下的兼容性',
            status: TaskStatus.NOT_STARTED,
            priority: TaskPriority.MEDIUM,
            assignee: mockUsers[2],
            creator: mockUsers[0],
            startDate: '2024-02-01T00:00:00Z',
            dueDate: '2024-02-10T00:00:00Z',
            milestone: 'M1 - 技术选型',
            groupId: 'group-1',
            createdAt: '2024-01-16T10:00:00Z',
            updatedAt: '2024-01-16T10:00:00Z',
            subTasks: [
              { id: 'subtask-4', title: '分析 package.json', completed: false, createdAt: '2024-01-16T10:00:00Z', updatedAt: '2024-01-16T10:00:00Z' },
              { id: 'subtask-5', title: '测试关键依赖', completed: false, createdAt: '2024-01-16T10:00:00Z', updatedAt: '2024-01-16T10:00:00Z' },
            ],
            cards: [],
            tags: ['依赖管理'],
            progress: 0,
          },
        ],
      },
      {
        id: 'group-2',
        title: '进行中',
        color: '#1890ff',
        order: 1,
        createdAt: '2024-01-15T10:00:00Z',
        updatedAt: '2024-01-15T10:00:00Z',
        tasks: [
          {
            id: 'task-3',
            title: '搭建开发环境',
            description: '配置 Vue 3 + Vite 开发环境',
            status: TaskStatus.IN_PROGRESS,
            priority: TaskPriority.HIGH,
            assignee: mockUsers[0],
            creator: mockUsers[0],
            startDate: '2024-01-20T00:00:00Z',
            dueDate: '2024-01-30T00:00:00Z',
            milestone: 'M2 - 环境搭建',
            groupId: 'group-2',
            createdAt: '2024-01-17T10:00:00Z',
            updatedAt: '2024-01-22T14:30:00Z',
            subTasks: [
              { id: 'subtask-6', title: '安装 Vue 3', completed: true, createdAt: '2024-01-17T10:00:00Z', updatedAt: '2024-01-20T09:00:00Z' },
              { id: 'subtask-7', title: '配置 Vite', completed: true, createdAt: '2024-01-17T10:00:00Z', updatedAt: '2024-01-21T11:00:00Z' },
              { id: 'subtask-8', title: '配置 TypeScript', completed: false, createdAt: '2024-01-17T10:00:00Z', updatedAt: '2024-01-17T10:00:00Z' },
              { id: 'subtask-9', title: '配置 ESLint', completed: false, createdAt: '2024-01-17T10:00:00Z', updatedAt: '2024-01-17T10:00:00Z' },
            ],
            cards: [
              { id: 'card-2', title: '环境配置清单', description: '开发环境配置步骤', content: '详细的配置步骤和命令', createdAt: '2024-01-17T10:00:00Z', updatedAt: '2024-01-20T15:00:00Z' },
            ],
            tags: ['环境配置', '基础设施'],
            progress: 50,
          },
          {
            id: 'task-4',
            title: '核心组件迁移',
            description: '迁移最重要的基础组件到 Vue 3',
            status: TaskStatus.IN_PROGRESS,
            priority: TaskPriority.URGENT,
            assignee: mockUsers[1],
            creator: mockUsers[0],
            startDate: '2024-01-22T00:00:00Z',
            dueDate: '2024-02-15T00:00:00Z',
            milestone: 'M3 - 核心功能',
            groupId: 'group-2',
            createdAt: '2024-01-18T10:00:00Z',
            updatedAt: '2024-01-23T16:45:00Z',
            subTasks: [
              { id: 'subtask-10', title: '迁移 Button 组件', completed: true, createdAt: '2024-01-18T10:00:00Z', updatedAt: '2024-01-22T14:00:00Z' },
              { id: 'subtask-11', title: '迁移 Input 组件', completed: false, createdAt: '2024-01-18T10:00:00Z', updatedAt: '2024-01-18T10:00:00Z' },
              { id: 'subtask-12', title: '迁移 Modal 组件', completed: false, createdAt: '2024-01-18T10:00:00Z', updatedAt: '2024-01-18T10:00:00Z' },
            ],
            cards: [
              { id: 'card-3', title: '组件迁移指南', description: 'Vue 2 到 Vue 3 组件迁移要点', content: '详细的迁移步骤和注意事项', createdAt: '2024-01-18T10:00:00Z', updatedAt: '2024-01-22T10:00:00Z' },
            ],
            tags: ['组件迁移', '紧急'],
            progress: 33,
          },
        ],
      },
      {
        id: 'group-3',
        title: '已完成',
        color: '#52c41a',
        order: 2,
        createdAt: '2024-01-15T10:00:00Z',
        updatedAt: '2024-01-15T10:00:00Z',
        tasks: [
          {
            id: 'task-5',
            title: '项目立项',
            description: '完成项目立项和资源申请',
            status: TaskStatus.COMPLETED,
            priority: TaskPriority.HIGH,
            assignee: mockUsers[0],
            creator: mockUsers[0],
            startDate: '2024-01-10T00:00:00Z',
            dueDate: '2024-01-15T00:00:00Z',
            milestone: 'M0 - 项目启动',
            groupId: 'group-3',
            createdAt: '2024-01-10T10:00:00Z',
            updatedAt: '2024-01-15T17:00:00Z',
            subTasks: [
              { id: 'subtask-13', title: '撰写项目计划书', completed: true, createdAt: '2024-01-10T10:00:00Z', updatedAt: '2024-01-12T16:00:00Z' },
              { id: 'subtask-14', title: '申请开发资源', completed: true, createdAt: '2024-01-10T10:00:00Z', updatedAt: '2024-01-13T14:00:00Z' },
              { id: 'subtask-15', title: '组建开发团队', completed: true, createdAt: '2024-01-10T10:00:00Z', updatedAt: '2024-01-15T10:00:00Z' },
            ],
            cards: [
              { id: 'card-4', title: '项目计划书', description: '详细的项目规划文档', content: '项目背景、目标、时间计划等', createdAt: '2024-01-10T10:00:00Z', updatedAt: '2024-01-12T16:00:00Z' },
            ],
            tags: ['项目管理', '已完成'],
            progress: 100,
          },
        ],
      },
      {
        id: 'group-4',
        title: '待验收',
        color: '#faad14',
        order: 3,
        createdAt: '2024-01-15T10:00:00Z',
        updatedAt: '2024-01-15T10:00:00Z',
        tasks: [],
      },
    ],
  },
  {
    id: 'project-2',
    title: '移动端 App 开发',
    description: '开发公司移动端应用，支持 iOS 和 Android 平台',
    creator: mockUsers[1],
    members: mockUsers.slice(1, 5),
    createdAt: '2024-01-10T08:00:00Z',
    updatedAt: '2024-01-25T12:00:00Z',
    groups: [
      {
        id: 'group-5',
        title: '需求分析',
        color: '#f5f5f5',
        order: 0,
        createdAt: '2024-01-10T08:00:00Z',
        updatedAt: '2024-01-10T08:00:00Z',
        tasks: [
          {
            id: 'task-6',
            title: '用户需求调研',
            description: '收集和分析用户需求，制定产品功能清单',
            status: TaskStatus.COMPLETED,
            priority: TaskPriority.HIGH,
            assignee: mockUsers[2],
            creator: mockUsers[1],
            startDate: '2024-01-10T00:00:00Z',
            dueDate: '2024-01-20T00:00:00Z',
            milestone: 'M1 - 需求确认',
            groupId: 'group-5',
            createdAt: '2024-01-10T08:00:00Z',
            updatedAt: '2024-01-20T18:00:00Z',
            subTasks: [
              { id: 'subtask-16', title: '用户访谈', completed: true, createdAt: '2024-01-10T08:00:00Z', updatedAt: '2024-01-15T14:00:00Z' },
              { id: 'subtask-17', title: '竞品分析', completed: true, createdAt: '2024-01-10T08:00:00Z', updatedAt: '2024-01-18T16:00:00Z' },
              { id: 'subtask-18', title: '需求文档整理', completed: true, createdAt: '2024-01-10T08:00:00Z', updatedAt: '2024-01-20T10:00:00Z' },
            ],
            cards: [
              { id: 'card-5', title: '需求调研报告', description: '用户需求分析和功能规划', content: '详细的需求分析报告', createdAt: '2024-01-10T08:00:00Z', updatedAt: '2024-01-20T18:00:00Z' },
            ],
            tags: ['需求分析', '用户研究'],
            progress: 100,
          },
        ],
      },
      {
        id: 'group-6',
        title: '设计开发',
        color: '#1890ff',
        order: 1,
        createdAt: '2024-01-10T08:00:00Z',
        updatedAt: '2024-01-10T08:00:00Z',
        tasks: [
          {
            id: 'task-7',
            title: 'UI 设计',
            description: '设计 App 的用户界面和交互流程',
            status: TaskStatus.IN_PROGRESS,
            priority: TaskPriority.HIGH,
            assignee: mockUsers[3],
            creator: mockUsers[1],
            startDate: '2024-01-21T00:00:00Z',
            dueDate: '2024-02-10T00:00:00Z',
            milestone: 'M2 - 设计完成',
            groupId: 'group-6',
            createdAt: '2024-01-19T08:00:00Z',
            updatedAt: '2024-01-25T14:30:00Z',
            subTasks: [
              { id: 'subtask-19', title: '制作线框图', completed: true, createdAt: '2024-01-19T08:00:00Z', updatedAt: '2024-01-23T12:00:00Z' },
              { id: 'subtask-20', title: '设计视觉稿', completed: false, createdAt: '2024-01-19T08:00:00Z', updatedAt: '2024-01-19T08:00:00Z' },
              { id: 'subtask-21', title: '制作交互原型', completed: false, createdAt: '2024-01-19T08:00:00Z', updatedAt: '2024-01-19T08:00:00Z' },
            ],
            cards: [
              { id: 'card-6', title: '设计规范', description: 'App 设计系统和规范', content: '颜色、字体、组件规范等', createdAt: '2024-01-19T08:00:00Z', updatedAt: '2024-01-23T15:00:00Z' },
            ],
            tags: ['UI设计', '用户体验'],
            progress: 40,
          },
        ],
      },
    ],
  },
];

// Simulate API delay
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const mockProjectApi = {
  // Get all projects
  async getProjects(): Promise<Project[]> {
    await delay(500);
    return mockProjects.map(p => JSON.parse(JSON.stringify(p)) as Project);
  },

  // Get single project
  async getProject(projectId: string): Promise<Project> {
    await delay(300);
    const project = mockProjects.find(p => p.id === projectId);
    if (!project) {
      throw new Error('Project not found');
    }
    return JSON.parse(JSON.stringify(project)) as Project;
  },

  // Create project
  async createProject(projectData: Partial<Project>): Promise<Project> {
    await delay(800);
    const newProject: Project = {
      id: `project-${Date.now()}`,
      title: projectData.title || 'New Project',
      description: projectData.description || '',
      creator: projectData.creator || mockUsers[0],
      members: projectData.members || [mockUsers[0]],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      groups: [
        {
          id: `group-${Date.now()}`,
          title: '待开始',
          color: '#f5f5f5',
          order: 0,
          tasks: [],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: `group-${Date.now() + 1}`,
          title: '进行中',
          color: '#1890ff',
          order: 1,
          tasks: [],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
        {
          id: `group-${Date.now() + 2}`,
          title: '已完成',
          color: '#52c41a',
          order: 2,
          tasks: [],
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        },
      ],
    };
    // 安全地添加项目，避免不可扩展对象错误
    mockProjects = [...mockProjects, newProject];
    return newProject;
  },

  // Update project
  async updateProject(projectId: string, data: Partial<Project>): Promise<Project> {
    await delay(500);
    const index = mockProjects.findIndex(p => p.id === projectId);
    if (index === -1) {
      throw new Error('Project not found');
    }
    // 深拷贝后写回，避免被外部冻结引用污染
    const current = JSON.parse(JSON.stringify(mockProjects[index])) as Project;
    const updated: Project = {
      ...current,
      ...data,
      updatedAt: new Date().toISOString(),
    } as Project;
    mockProjects[index] = updated;
    return JSON.parse(JSON.stringify(updated)) as Project;
  },

  // Create task
  async createTask(projectId: string, groupId: string, taskData: Partial<Task>): Promise<Task> {
    await delay(600);

    console.log('Creating task:', { projectId, groupId, taskData });

    const projIndex = mockProjects.findIndex(p => p.id === projectId);
    const project = mockProjects[projIndex];
    if (!project) {
      console.error('Project not found:', projectId);
      throw new Error(`Project not found: ${projectId}`);
    }

    const group = project.groups.find(g => g.id === groupId);
    if (!group) {
      console.error('Group not found:', { groupId, availableGroups: project.groups.map(g => g.id) });
      throw new Error(`Group not found: ${groupId}`);
    }

    // 开发模式下检查对象可扩展性
    if (process.env.NODE_ENV === 'development') {
      if (!Object.isExtensible(group.tasks)) {
        console.warn('Group tasks array is not extensible, using safe array replacement');
      }
    }

    // 验证必需字段
    if (!taskData.title?.trim()) {
      throw new Error('Task title is required');
    }

    if (!taskData.creator) {
      console.error('Task creator is missing:', taskData);
      throw new Error('Task creator is required');
    }

    const newTask: Task = {
      id: `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      title: taskData.title.trim(),
      description: taskData.description || '',
      status: taskData.status || TaskStatus.NOT_STARTED,
      priority: taskData.priority || TaskPriority.MEDIUM,
      assignee: taskData.assignee,
      creator: taskData.creator,
      startDate: taskData.startDate,
      dueDate: taskData.dueDate,
      milestone: taskData.milestone,
      groupId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      subTasks: taskData.subTasks || [],
      cards: taskData.cards || [],
      tags: taskData.tags || [],
      progress: 0,
    };

    // 写回为新的 groups（不可变），确保不依赖可能被冻结的原始引用
    project.groups = project.groups.map(g => (g.id === groupId ? { ...g, tasks: [...g.tasks, newTask] } : g));
    // 将变更后的项目写回 mockProjects，避免后续引用被外部冻结
    mockProjects[projIndex] = project;
    console.log('Task created successfully:', newTask);
    return JSON.parse(JSON.stringify(newTask)) as Task;
  },

  // Update task
  async updateTask(projectId: string, taskId: string, data: Partial<Task>): Promise<Task> {
    await delay(400);
    const projIndex = mockProjects.findIndex(p => p.id === projectId);
    const project = mockProjects[projIndex];
    if (!project) {
      throw new Error('Project not found');
    }

    let task: Task | undefined;
    let group: TaskGroup | undefined;

    for (const g of project.groups) {
      task = g.tasks.find(t => t.id === taskId);
      if (task) {
        group = g;
        break;
      }
    }

    if (!task || !group) {
      throw new Error('Task not found');
    }

    // 以不可变方式更新任务，避免写入只读对象
    const updatedTask: Task = {
      ...task,
      ...data,
      updatedAt: new Date().toISOString(),
    } as Task;
    group.tasks = group.tasks.map(t => (t.id === taskId ? updatedTask : t));
    // 写回项目
    project.groups = project.groups.map(g => (g.id === group!.id ? { ...g, tasks: group!.tasks } : g));
    mockProjects[projIndex] = project;

    // Recalculate progress if subtasks were updated
    if (data.subTasks) {
      const completedSubTasks = updatedTask.subTasks.filter(st => st.completed).length;
      const progress = updatedTask.subTasks.length > 0
        ? Math.round((completedSubTasks / updatedTask.subTasks.length) * 100)
        : (updatedTask.status === TaskStatus.COMPLETED ? 100 : 0);
      const finalTask: Task = { ...updatedTask, progress };
      group.tasks = group.tasks.map(t => (t.id === taskId ? finalTask : t));
      project.groups = project.groups.map(g => (g.id === group!.id ? { ...g, tasks: group!.tasks } : g));
      mockProjects[projIndex] = project;
      return JSON.parse(JSON.stringify(finalTask)) as Task;
    }

    return JSON.parse(JSON.stringify(updatedTask)) as Task;
  },

  // Delete task
  async deleteTask(projectId: string, taskId: string): Promise<void> {
    await delay(300);
    const project = mockProjects.find(p => p.id === projectId);
    if (!project) {
      throw new Error('Project not found');
    }

    for (const group of project.groups) {
      const taskIndex = group.tasks.findIndex(t => t.id === taskId);
      if (taskIndex !== -1) {
        // 安全地删除任务，避免数组操作错误
        group.tasks = group.tasks.filter(t => t.id !== taskId);
        return;
      }
    }

    throw new Error('Task not found');
  },

  // Move task
  async moveTask(
    projectId: string,
    taskId: string,
    sourceGroupId: string,
    targetGroupId: string,
    targetIndex: number
  ): Promise<Project> {
    await delay(400);

    console.log('Moving task:', {
      projectId,
      taskId,
      sourceGroupId,
      targetGroupId,
      targetIndex
    });

    const projIndex = mockProjects.findIndex(p => p.id === projectId);
    const project = mockProjects[projIndex];
    if (!project) {
      console.error('Project not found for move operation:', projectId);
      throw new Error(`Project not found: ${projectId}`);
    }

    const sourceGroup = project.groups.find(g => g.id === sourceGroupId);
    const targetGroup = project.groups.find(g => g.id === targetGroupId);

    if (!sourceGroup) {
      console.error('Source group not found:', {
        sourceGroupId,
        availableGroups: project.groups.map(g => g.id)
      });
      throw new Error(`Source group not found: ${sourceGroupId}`);
    }

    if (!targetGroup) {
      console.error('Target group not found:', {
        targetGroupId,
        availableGroups: project.groups.map(g => g.id)
      });
      throw new Error(`Target group not found: ${targetGroupId}`);
    }

    const taskIndex = sourceGroup.tasks.findIndex(t => t.id === taskId);
    if (taskIndex === -1) {
      console.error('Task not found in source group:', {
        taskId,
        sourceGroupId,
        availableTasks: sourceGroup.tasks.map(t => t.id)
      });
      throw new Error(`Task not found: ${taskId}`);
    }

    // 验证目标索引
    if (targetIndex < 0 || targetIndex > targetGroup.tasks.length) {
      console.error('Invalid target index:', {
        targetIndex,
        maxIndex: targetGroup.tasks.length
      });
      throw new Error(`Invalid target index: ${targetIndex}`);
    }

    // 开发模式下检查对象可扩展性
    if (process.env.NODE_ENV === 'development') {
      if (!Object.isExtensible(sourceGroup.tasks)) {
        console.warn('Source group tasks array is not extensible, using safe array replacement');
      }
      if (!Object.isExtensible(targetGroup.tasks)) {
        console.warn('Target group tasks array is not extensible, using safe array replacement');
      }
    }

    // 安全地移动任务，避免数组操作错误
    const task = sourceGroup.tasks[taskIndex];
    const updatedTask = {
      ...task,
      groupId: targetGroupId,
      updatedAt: new Date().toISOString()
    };

    if (sourceGroupId === targetGroupId) {
      // 同组内重排：移除后插入（注意索引调整）
      const without = sourceGroup.tasks.filter(t => t.id !== task.id);
      const adjustedIndex = targetIndex > sourceGroup.tasks.findIndex(t => t.id === task.id)
        ? Math.max(0, targetIndex - 1)
        : targetIndex;
      const reordered = [
        ...without.slice(0, adjustedIndex),
        updatedTask,
        ...without.slice(adjustedIndex)
      ];
      project.groups = project.groups.map(g => (g.id === sourceGroupId ? { ...g, tasks: reordered } : g));
    } else {
      // 跨组移动
      const newSourceTasks = sourceGroup.tasks.filter(t => t.id !== task.id);
      const targetTasks = [...targetGroup.tasks];
      targetTasks.splice(targetIndex, 0, updatedTask);
      project.groups = project.groups.map(g => {
        if (g.id === sourceGroupId) return { ...g, tasks: newSourceTasks };
        if (g.id === targetGroupId) return { ...g, tasks: targetTasks };
        return g;
      });
    }
    mockProjects[projIndex] = project;

    console.log('Task moved successfully:', {
      taskId: task.id,
      fromGroup: sourceGroupId,
      toGroup: targetGroupId,
      newIndex: targetIndex
    });

    return JSON.parse(JSON.stringify(project)) as Project;
  },

  // Create group
  async createGroup(projectId: string, groupData: Partial<TaskGroup>): Promise<TaskGroup> {
    await delay(500);
    const project = mockProjects.find(p => p.id === projectId);
    if (!project) {
      throw new Error('Project not found');
    }

    const newGroup: TaskGroup = {
      id: `group-${Date.now()}`,
      title: groupData.title || 'New Group',
      color: groupData.color || '#f5f5f5',
      order: project.groups.length,
      tasks: [],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };

    // 安全地添加分组，避免不可扩展对象错误
    project.groups = [...project.groups, newGroup];
    return newGroup;
  },

  // Update group
  async updateGroup(projectId: string, groupId: string, data: Partial<TaskGroup>): Promise<TaskGroup> {
    await delay(300);
    const projIndex = mockProjects.findIndex(p => p.id === projectId);
    const project = mockProjects[projIndex];
    if (!project) {
      throw new Error('Project not found');
    }

    const group = project.groups.find(g => g.id === groupId);
    if (!group) {
      throw new Error('Group not found');
    }

    const updated: TaskGroup = {
      ...group,
      ...data,
      updatedAt: new Date().toISOString(),
    } as TaskGroup;
    project.groups = project.groups.map(g => (g.id === groupId ? updated : g));
    mockProjects[projIndex] = project;
    return JSON.parse(JSON.stringify(updated)) as TaskGroup;
  },

  // Delete group
  async deleteGroup(projectId: string, groupId: string): Promise<void> {
    await delay(300);
    const projIndex = mockProjects.findIndex(p => p.id === projectId);
    const project = mockProjects[projIndex];
    if (!project) {
      throw new Error('Project not found');
    }

    const groupIndex = project.groups.findIndex(g => g.id === groupId);
    if (groupIndex === -1) {
      throw new Error('Group not found');
    }

    // Move tasks to first group if deleting non-first group
    const groupToDelete = project.groups[groupIndex];
    if (groupToDelete.tasks.length > 0 && project.groups.length > 1) {
      const firstGroup = project.groups[0].id === groupId ? project.groups[1] : project.groups[0];
      const movedTasks = groupToDelete.tasks.map(task => ({
        ...task,
        groupId: firstGroup.id
      }));
      // 安全地添加任务到目标分组
      firstGroup.tasks = [...firstGroup.tasks, ...movedTasks];
    }

    // 安全地删除分组，避免数组操作错误
    project.groups = project.groups.filter(g => g.id !== groupId);
    mockProjects[projIndex] = project;
  },

  // Get users (for assignee selection)
  async getUsers(): Promise<User[]> {
    await delay(200);
    return [...mockUsers];
  },

  // Copy task
  async copyTask(projectId: string, taskId: string, copyOptions: {
    title?: boolean;
    description?: boolean;
    assignee?: boolean;
    dueDate?: boolean;
    subTasks?: boolean;
    cards?: boolean;
    tags?: boolean;
  }): Promise<Task> {
    await delay(500);
    const project = mockProjects.find(p => p.id === projectId);
    if (!project) {
      throw new Error('Project not found');
    }

    let originalTask: Task | undefined;
    let targetGroup: TaskGroup | undefined;

    for (const group of project.groups) {
      originalTask = group.tasks.find(t => t.id === taskId);
      if (originalTask) {
        targetGroup = group;
        break;
      }
    }

    if (!originalTask || !targetGroup) {
      throw new Error('Task not found');
    }

    const newTask: Task = {
      id: `task-${Date.now()}`,
      title: copyOptions.title ? `${originalTask.title} (副本)` : 'New Task',
      description: copyOptions.description ? originalTask.description : '',
      status: TaskStatus.NOT_STARTED,
      priority: originalTask.priority,
      assignee: copyOptions.assignee ? originalTask.assignee : undefined,
      creator: originalTask.creator,
      startDate: undefined,
      dueDate: copyOptions.dueDate ? originalTask.dueDate : undefined,
      milestone: originalTask.milestone,
      groupId: originalTask.groupId,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      subTasks: copyOptions.subTasks ? originalTask.subTasks.map(st => ({
        ...st,
        id: `subtask-${Date.now()}-${Math.random()}`,
        completed: false,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      })) : [],
      cards: copyOptions.cards ? originalTask.cards.map(card => ({
        ...card,
        id: `card-${Date.now()}-${Math.random()}`,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      })) : [],
      tags: copyOptions.tags ? [...(originalTask.tags || [])] : [],
      progress: 0,
    };

    targetGroup.tasks.push(newTask);
    return JSON.parse(JSON.stringify(newTask)) as Task;
  },
};
